package team.future.joke.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import team.future.joke.constant.CollectorConstants;
import team.future.joke.entity.Joke;
import team.future.joke.param.JokeParam;
import team.future.joke.service.JokeReceiveService;
import team.future.joke.service.JokeService;
import team.future.joke.util.WebClientUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * Title: ReceiveController.java<br>
 * Description: <br>
 * Copyright (c) 未来工作室版权所有 2015    <br>
 * Create DateTime: 2015年9月18日 下午5:20:39 <br>
 * @author futurezhu
*/
@Controller
public class DataSyncController {

	@Autowired
	private JokeReceiveService jokeReceiveService;
	@Autowired
	private JokeService jokeService;

	@RequestMapping("/joke/receive/syncData")
	@ResponseBody
	public String receiveSyncData(@RequestParam("syncDatas") String syncDatas) {
		JSONArray array = JSONArray.parseArray(syncDatas);
		jokeReceiveService.syncData(array);
		return "success";
	}

	@RequestMapping("/joke/send/syncData")
	@ResponseBody
	public String sendSyncData(@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex) {
		StringBuffer param = new StringBuffer();
		JokeParam p = new JokeParam();
		p.setPageSize(100);
		p.setPageIndex(pageIndex);
		List<Joke> list = jokeService.getJokeListPage(p);
		JSONArray array = new JSONArray();
		for (Joke j : list) {
			JSONObject jo = new JSONObject();
			jo.put("id", j.getId());
			jo.put("nid", j.getNid());
			jo.put("title", j.getTitle());
			jo.put("content", j.getContent());
			jo.put("type", j.getType());
			jo.put("status", j.getStatus());
			array.add(jo);
		}
		param.append("syncDatas=").append(array.toString());
		WebClientUtil.post(CollectorConstants.REAL_DOMAIN + "/joke/receive/syncData.future", param.toString());
		return "success";
	}
}
